import requests
from src.log import log
from src.config_util import Config

from src.common import now_time, JenkinsUtil


class WeChatSend:
    """
    企业微信消息通知
    """

    def __init__(self, metrics):
        self.metrics = metrics
        self.headers = {"Content-Type": "application/json"}
        self.conf = Config()
        self.webhook = self.conf.get_conf("wechat").get("webhook")
        self.jenkins_info = JenkinsUtil()

    def send_text(self, content, mentioned_mobile_list=None):
        """
        发送文本类型通知
        :param content: 文本内容，最长不超过2048个字节，必须是utf8编码
        :param mentioned_mobile_list: 手机号列表，提醒手机号对应的群成员(@某个成员)，@all表示提醒所有人
        :return:
        """
        _data = {"msgtype": "text", "text": {"content": content, "mentioned_list": None,
                                             "mentioned_mobile_list": mentioned_mobile_list}}

        # 判断手机号码列表中得数据类型，如果为int类型，发送得消息会乱码
        if len(mentioned_mobile_list) >= 1:
            for i in mentioned_mobile_list:
                requests.post(url=self.webhook, json=_data, headers=self.headers)

    def send_markdown(self, content):
        """
        发送 MarkDown 类型消息
        :param content: 消息内容，markdown形式
        :return:
        """
        _data = {"msgtype": "markdown", "markdown": {"content": content}}
        res = requests.post(url=self.webhook, json=_data, headers=self.headers)
        if res.json()['errcode'] != 0:
            log.error(res.json())
            raise Exception("企业微信「MarkDown类型」消息发送失败")

    def _upload_file(self, file):
        """
        先将文件上传到临时媒体库
        """
        key = self.webhook.split("key=")[1]
        url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={key}&type=file"
        data = {"file": open(file, "rb")}
        res = requests.post(url, files=data).json()
        return res['media_id']

    def send_file_msg(self, file):
        """
        发送文件类型的消息
        @return:
        """

        _data = {"msgtype": "file", "file": {"media_id": self._upload_file(file)}}
        requests.post(url=self.webhook, json=_data, headers=self.headers)

    def send(self):

        """ 发送企业微信通知 """
        text = f"""
            【自动化测试结果通知】
            项目名称：<font color=\"info\">{self.jenkins_info.job_name}</font>
            构建编号：<font color=\"info\">#{self.jenkins_info.build_number}</font>
            测试环境：<font color=\"info\">{self.conf.get_conf('env')}</font>
            [测试报告]({self.jenkins_info.allure_url})
            [构建地址]({self.jenkins_info.build_url})
            **执行结果**
            用例总数：<font color=\"info\">{self.metrics.total}</font>                                    
            成功用例数：<font color=\"info\">{self.metrics.passed}</font>
            失败用例数：`{self.metrics.failed}个`
            异常用例数：`{self.metrics.error}个`
            跳过用例数：<font color=\"warning\">{self.metrics.skipped}个</font>
            <font color=\"info\">通过率 : {self.metrics.pass_rate}%</font>
            失败用例：<font color=\"info\">{self.metrics.failed_cases}</font>         
            用例执行时长：<font color=\"warning\">{self.metrics.duration}</font>
            通知时间：<font color=\"comment\">{now_time()}</font>
            """
        self.send_markdown(text)
